package com.tom.demo.security;


import com.fasterxml.jackson.annotation.JsonIgnore;
import com.tom.demo.common.entity.SysUser;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: LanQiang
 * @Date: 2023/01/16/17:34
 * @Description: 查询出来的用户信息交给security
  注意：如果你存进redis中的是整个DetailsUser对象，那么请将全参数构造和无参数构造都加上
 以免出现从redis取出来的时候，出现反序化异常错误
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DetailsUser implements UserDetails, Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 从这个SysUser用来获取
     * 我们从数据库中查询出来user信息所对应的权限信息
     */
    private SysUser sysUser;
    /**
     * 存储用户的角色信息
     */
    private Set<String> roles;
    /**
     * 存储用户权限信息
     */
    private Set<String> permissions;
    /**
     * @description 生成一个三个参数的构造方法
     * @param sysUser
     * @param roles
     * @param permissions
     * @author lanqiang
     * @date 2022/11/1 0001
     */
    public DetailsUser(SysUser sysUser, Set<String> roles, Set<String> permissions) {
        this.sysUser = sysUser;
        this.roles = roles;
        this.permissions = permissions;
    }
    //存储SpringSecurity所需要的权限集合
    @JsonIgnore//不让它序列化到redis中
    private Set<GrantedAuthority> authorities = new HashSet<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //获取权限，优化
        if(!this.authorities.isEmpty()){
            return this.authorities;
        }
        //封装角色信息到SimpleGrantedAuthority集合中
        Set<SimpleGrantedAuthority> rolesList = roles.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toSet());
        //封装权限信息到SimpleGrantedAuthority集合中
        Set<SimpleGrantedAuthority> permissionsList = permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toSet());
        authorities.addAll(rolesList);
        authorities.addAll(permissionsList);
        return authorities;
    }
    @Override
    @JsonIgnore
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    @JsonIgnore
    public String getUsername() {
        return sysUser.getUsername();
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isEnabled() {
        return true;
    }
}